<template>
  <div class="profile">
    <div class="profile-header">
      <h2>个人中心</h2>
    </div>

    <div class="profile-content">
      <el-card class="user-info-card">
        <template #header>
          <div class="card-header">
            <span>个人信息</span>
            <div class="header-buttons">
              <el-button 
                v-if="hasPermission('edit-profile')"
                type="primary" 
                size="small"
                @click="showEditProfile = true"
              >
                编辑信息
              </el-button>
            <el-button 
              v-if="hasPermission('change-password')"
                type="success" 
              size="small"
              @click="showChangePassword = true"
            >
              修改密码
            </el-button>
            </div>
          </div>
        </template>
        
        <div class="user-info" v-if="userInfo">
          <div class="info-item">
            <span class="label">用户ID：</span>
            <span class="value">{{ userInfo.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户名：</span>
            <span class="value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">昵称：</span>
            <span class="value">{{ userInfo.nickname }}</span>
          </div>
          <div class="info-item">
            <span class="label">邮箱：</span>
            <span class="value">{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号：</span>
            <span class="value">{{ userInfo.phone }}</span>
          </div>
          <div class="info-item">
            <span class="label">角色：</span>
            <span class="value">
              <el-tag
                v-for="role in userInfo.roles"
                :key="role"
                :type="getRoleType(role)"
                style="margin-right: 8px;"
              >
                {{ role }}
              </el-tag>
            </span>
          </div>

          <!-- 学生专用信息 -->
          <template v-if="userInfo.roles && userInfo.roles.includes('学生')">
            <div class="info-item" v-if="userInfo.currentAcademicYear">
              <span class="label">当前学年学期：</span>
              <span class="value">{{ userInfo.currentAcademicYear }}</span>
            </div>
            <div class="info-item" v-if="userInfo.currentAcademicYearOnly">
              <span class="label">当前学年：</span>
              <span class="value">{{ userInfo.currentAcademicYearOnly }}</span>
            </div>
            <div class="info-item" v-if="userInfo.currentSemester">
              <span class="label">当前学期：</span>
              <span class="value">第{{ userInfo.currentSemester }}学期</span>
            </div>
          </template>
        </div>
      </el-card>

      <!-- 组织信息卡片 -->
      <el-card class="organization-info-card" v-if="userInfo && userInfo.organizations && userInfo.organizations.length > 0">
        <template #header>
          <div class="card-header">
            <span>组织信息</span>
          </div>
        </template>
        
        <div class="organization-info">
          <div 
            v-for="(org, index) in userInfo.organizations" 
            :key="org.id" 
            class="org-item"
            :class="{ 'org-divider': index > 0 }"
          >
            <div class="org-header">
              <el-tag :type="getOrgType(org.orgType)" size="small">
                {{ getOrgTypeName(org.orgType) }}
              </el-tag>
              <span class="org-name">{{ org.orgName }}</span>
            </div>
            
            <div class="org-path" v-if="org.collegeName || org.majorName || org.className">
              <div class="path-item" v-if="org.collegeName">
                <span class="path-label">学院：</span>
                <span class="path-value">{{ org.collegeName }}</span>
              </div>
              <div class="path-item" v-if="org.majorName">
                <span class="path-label">专业：</span>
                <span class="path-value">{{ org.majorName }}</span>
              </div>
              <div class="path-item" v-if="org.className">
                <span class="path-label">班级：</span>
                <span class="path-value">{{ org.className }}</span>
              </div>
            </div>
            
            <div class="org-details">
              <div class="detail-item">
                <span class="detail-label">组织编码：</span>
                <span class="detail-value">{{ org.orgCode }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">组织层级：</span>
                <span class="detail-value">第{{ org.orgLevel }}级</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 编辑个人信息对话框 -->
    <el-dialog v-model="showEditProfile" title="编辑个人信息" width="450px">
      <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="80px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditProfile">取消</el-button>
        <el-button type="primary" @click="handleUpdateProfile" :loading="profileLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showChangePassword" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeChangePassword">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateProfile, changePassword } from '../api/auth'
import { useUserStore } from '../stores/user'

const userStore = useUserStore()
const userInfo = computed(() => userStore.currentUser)

const showEditProfile = ref(false)
    const showChangePassword = ref(false)
const profileLoading = ref(false)
const passwordLoading = ref(false)
const profileFormRef = ref()
const passwordFormRef = ref()

const profileForm = reactive({
  nickname: '',
  email: '',
  phone: ''
})
    
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

    // 检查按钮权限
    const hasPermission = (permission) => {
      return window.userButtons && window.userButtons.includes(permission)
    }

    // 获取角色类型
    const getRoleType = (role) => {
      switch (role) {
        case '管理员':
          return 'danger'
        case '学生':
          return 'primary'
        case '教师':
          return 'success'
        default:
          return 'info'
      }
    }

    // 获取组织类型
    const getOrgType = (orgType) => {
      switch (orgType) {
        case 'COLLEGE':
          return 'danger'
        case 'MAJOR':
          return 'warning'
        case 'CLASS':
          return 'success'
        default:
          return 'info'
      }
    }

    // 获取组织类型名称
    const getOrgTypeName = (orgType) => {
      switch (orgType) {
        case 'COLLEGE':
          return '学院'
        case 'MAJOR':
          return '专业'
        case 'CLASS':
          return '班级'
        default:
          return '未知'
      }
    }

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await getUserInfo()
        userStore.saveUser(response.data)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
      }
    }

// 初始化编辑表单
const initProfileForm = () => {
  if (userInfo.value) {
    profileForm.nickname = userInfo.value.nickname || ''
    profileForm.email = userInfo.value.email || ''
    profileForm.phone = userInfo.value.phone || ''
  }
}

// 重置编辑表单
const resetProfileForm = () => {
  profileForm.nickname = ''
  profileForm.email = ''
  profileForm.phone = ''
  if (profileFormRef.value) {
    profileFormRef.value.clearValidate()
  }
}

// 关闭编辑对话框
const closeEditProfile = () => {
  showEditProfile.value = false
  resetProfileForm()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

// 关闭修改密码对话框
const closeChangePassword = () => {
  showChangePassword.value = false
  resetPasswordForm()
}

// 更新个人信息
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    profileLoading.value = true
    
    const response = await updateProfile(profileForm)
    
    // 检查后端返回的结果
    if (response.data.code === 200) {
      ElMessage.success('个人信息更新成功')
      
      // 重新获取用户信息
      await fetchUserInfo()
      closeEditProfile()
    } else {
      ElMessage.error(response.data.message || '更新个人信息失败')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    // 处理网络错误或其他异常
    let errorMessage = '更新个人信息失败'
    
    if (error.response) {
      const responseData = error.response.data
      if (responseData && responseData.message) {
        errorMessage = responseData.message
      } else if (typeof responseData === 'string') {
        errorMessage = responseData
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    profileLoading.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    const response = await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    // 检查后端返回的结果
    if (response.data.code === 200) {
      ElMessage.success('密码修改成功')
      closeChangePassword()
    } else {
      ElMessage.error(response.data.message || '修改密码失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    // 处理网络错误或其他异常
    let errorMessage = '修改密码失败'
    
    if (error.response) {
      const responseData = error.response.data
      if (responseData && responseData.message) {
        errorMessage = responseData.message
      } else if (typeof responseData === 'string') {
        errorMessage = responseData
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    passwordLoading.value = false
  }
}

// 监听编辑对话框打开，初始化表单
const handleEditProfileOpen = () => {
  initProfileForm()
    }

    onMounted(() => {
      // 如果用户已登录但信息不完整，则从服务器获取最新信息
      if (userStore.isLoggedIn) {
        fetchUserInfo()
      }
    })

// 监听showEditProfile变化，当打开时初始化表单
import { watch } from 'vue'
watch(showEditProfile, (newVal) => {
  if (newVal) {
    handleEditProfileOpen()
  }
})
</script>

<style scoped>
.profile {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.profile-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.profile-header h2 {
  margin: 0;
  color: #333;
}

.profile-content {
  max-width: 600px;
}

.user-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.user-info {
  padding: 10px 0;
}

.organization-info-card {
  margin-bottom: 20px;
}

.organization-info {
  padding: 10px 0;
}

.org-item {
  padding: 15px 0;
}

.org-divider {
  border-top: 1px solid #f0f0f0;
}

.org-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.org-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-left: 10px;
}

.org-path {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.path-item {
  display: flex;
  margin-bottom: 5px;
}

.path-item:last-child {
  margin-bottom: 0;
}

.path-label {
  font-weight: bold;
  color: #666;
  min-width: 60px;
}

.path-value {
  color: #333;
  margin-left: 5px;
}

.org-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  font-weight: bold;
  color: #666;
  margin-right: 5px;
}

.detail-value {
  color: #333;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 600;
  color: #666;
  min-width: 100px;
}

.value {
  color: #333;
  font-weight: 500;
}
</style> 